package org.jeecg.modules.wangyue.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.digest.DigestUtils;
import org.jeecg.common.api.vo.Result;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

/**
 * http请求工具
 *
 * @author 62377
 */
public class DanMiSmsUtil {

    /**
     * url前半部分
     */
    public static final String BASE_URL = "https://openapi.danmi.com/distributor/sendSMS";

    /**
     * 开发者注册后系统自动生成的账号，可在官网登录后查看
     */
    public static final String ACCOUNT_SID = "df6f8d9745bec6c3ec71b41821a91825";

    /**
     * 开发者注册后系统自动生成的TOKEN，可在官网登录后查看
     */
    public static final String AUTH_TOKEN = "bdb7c7f820f12432753b4160709ec511";

    /**
     * 响应数据类型, JSON或XML
     */
    public static final String RESP_DATA_TYPE = "JSON";

    //通知模板
    public static final String NOTICE = "499507";
    //验证码模板
    public static final String VERIFICATION = "485515";

    /**
     * 构造通用参数timestamp、sig和respDataType
     *
     * @return
     */
    public static String createCommonParam(String sid, String token) {
        // 时间戳
        long timestamp = System.currentTimeMillis();
        // 签名
        String sig = DigestUtils.md5Hex(sid + token + timestamp);

        return "&timestamp=" + timestamp + "&sig=" + sig + "&respDataType=" + RESP_DATA_TYPE;
    }

    /**
     * post请求
     *
     * @param url  功能和操作
     * @param body 要post的数据
     * @return
     * @throws IOException
     */
    public static String post(String url, String body) {
        System.out.println("body:" + System.lineSeparator() + body);

        String result = "";
        try {
            OutputStreamWriter out = null;
            BufferedReader in = null;
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            // 设置连接参数
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(20000);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 提交数据
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(body);
            out.flush();

            // 读取返回数据
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line = "";
            boolean firstLine = true; // 读第一行不加换行符
            while ((line = in.readLine()) != null) {
                if (firstLine) {
                    firstLine = false;
                } else {
                    result += System.lineSeparator();
                }
                result += line;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 回调测试工具方法
     *
     * @param url
     * @return
     */
    public static String postHuiDiao(String url, String body) {
        String result = "";
        try {
            OutputStreamWriter out = null;
            BufferedReader in = null;
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            // 设置连接参数
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(20000);

            // 提交数据
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(body);
            out.flush();

            // 读取返回数据
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line = "";
            boolean firstLine = true; // 读第一行不加换行符
            while ((line = in.readLine()) != null) {
                if (firstLine) {
                    firstLine = false;
                } else {
                    result += System.lineSeparator();
                }
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Result<?> execute(String account, String message, String temp) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("accountSid").append("=").append(ACCOUNT_SID);
            sb.append("&to").append("=").append(account);
            sb.append("&param").append("=").append(URLEncoder.encode(message, "UTF-8"));
            sb.append("&templateid").append("=").append(temp);
            //sb.append("&smsContent").append("=").append( URLEncoder.encode("【旦米科技】您的验证码为123456，该验证码5分钟内有效。请勿泄漏于他人。","UTF-8"));
            //sb.append("&param").append("=").append(URLEncoder.encode("1","UTF-8"));
            //sb.append("&smsType").append("=").append("100000");

            String body = sb + createCommonParam(ACCOUNT_SID, AUTH_TOKEN);
            //String result = HttpUtil.post(Config.BASE_URL, body);
            String result = post(BASE_URL, body);
            System.out.println(result);
            Map<String, Object> map = JSON.parseObject(result, Map.class);
            String respCode = map.get("respCode").toString();
            if ("0000".equals(respCode)) {
                return Result.OK("短信发送成功");
            } else {
                return Result.error("短信发送失败！");
            }
        } catch (Exception e) {
            return Result.error("短信发送失败！");
        }
    }

    public static void main(String[] args) {
        DanMiSmsUtil am = new DanMiSmsUtil();
        try {
            String phoneCode = "JS12039475";
            am.execute("15875541127", phoneCode, DanMiSmsUtil.NOTICE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}